package com.kk.project.db.mysql.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.kk.project.db.mysql.utils.DbUtils;
import com.kk.project.db.mysql.utils.PropertiesUtils;

/**
 * 通过jdbc向blob字段插入图片
 * 
 * @author liujun
 * @version 1.0.0
 * @since 2017年8月30日 下午3:47:13
 */
public class JdbcBlogProc {

	public void instBlobImsg() {

		// 查询所有的表
		String sql = "INSERT INTO blobTable2 (id,img) VALUES(?,?)";

		Connection conn = null;
		PreparedStatement pstmt = null;
		int result = -1;
		try {
			// 初始化数据源信息
			DataSource dataSource = DruidDataSourceFactory
					.createDataSource(PropertiesUtils.getInstance().getProperties());

			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement(sql);

			File image = new File("D:/java/test/mysql/src/navicat112_mysql_cs_x64.zip");

			pstmt.setInt(1, 102);

			FileInputStream fis = new FileInputStream(image);
			pstmt.setBinaryStream(2, (InputStream) fis, (int) (image.length()));

			result = pstmt.executeUpdate();

			if (result > 0) {
				System.out.println("操作成功 ");
			} else {
				System.out.println("插入失败");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(pstmt);
			DbUtils.close(conn);
		}
	}

	public static void main(String[] args) {
		JdbcBlogProc blobTest = new JdbcBlogProc();

		blobTest.instBlobImsg();
		//blobTest.selectBolbProc();
	}

	public void selectBolbProc() {

		// 查询所有的表
		String sql = "select * from blobTable2 where id= 101";

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			// 初始化数据源信息
			DataSource dataSource = DruidDataSourceFactory
					.createDataSource(PropertiesUtils.getInstance().getProperties());

			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement(sql);

			rs = pstmt.executeQuery();

			while (rs.next()) {
				System.out.println(rs.getInt("id"));
				System.out.println(rs.getBlob("img").length());
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(rs);
			DbUtils.close(pstmt);
			DbUtils.close(conn);
		}

	}

}
